<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>PayPal + Google Pay Demo</title>

    <!-- PayPal JS SDK: 注意 components=googlepay -->
<#--    <script src="https://www.paypal.com/sdk/js?client-id=${clientId}&currency=${currency}&buyer-country=${buyerCountry}&merchant-id=${merchantId}&components=googlepay"></script>-->
    <script
            src="https://www.paypal.com/sdk/js?client-id=AYOeyCQvilLVKJGjslZfFSi_Nkl7A6OfXNarj5lS55iUcQXMhpp3AypVjAVkS_qvPcO5D415b9SnBFuN&buyer-country=US&currency=USD&components=buttons,card-fields&enable-funding=venmo"
            data-sdk-integration-source="developer-studio"
    ></script>

    <!-- Google Pay JS -->
    <script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script>

    <style>
        #container { margin-top: 20px; }
    </style>
</head>
<body>
<h2>Pay with Google Pay (via PayPal)</h2>
<div id="container">Loading payment methods...</div>
<pre id="log"></pre>

<script>
    function log(...args) {
        console.log(...args);
        const el = document.getElementById('log');
        el.textContent += args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ') + '\n';
    }

    // Called when Google Pay JS loaded (onload attribute)
    async function onGooglePayLoaded() {
        try {
            // 1) Ask PayPal's googlepay component for config (allowedPaymentMethods, merchantInfo, etc.)
            const googlePayConfig = await paypal.Googlepay().config();
            log("paypal.Googlepay().config() =>", googlePayConfig);

            // 2) Build Google isReadyToPay request using allowedPaymentMethods returned by PayPal
            const baseRequest = { apiVersion: 2, apiVersionMinor: 0 };
            const isReadyToPayRequest = Object.assign({}, baseRequest, {
                allowedPaymentMethods: googlePayConfig.allowedPaymentMethods
            });

            // 3) Create Google PaymentsClient
            const paymentsClient = new google.payments.api.PaymentsClient({environment: 'TEST'});

            // 4) Check device/browser capability
            const ready = await paymentsClient.isReadyToPay(isReadyToPayRequest);
            log("isReadyToPay:", ready);
            if (ready.result) {
                addGooglePayButton(paymentsClient, googlePayConfig);
            } else {
                document.getElementById('container').innerText = 'Google Pay not available on this device/browser.';
            }
        } catch (e) {
            console.error(e);
            log("Error in onGooglePayLoaded:", e);
            document.getElementById('container').innerText = 'Error initializing Google Pay.';
        }
    }

    function addGooglePayButton(paymentsClient, googlePayConfig) {
        const button = paymentsClient.createButton({
            onClick: function() { onGooglePaymentButtonClicked(paymentsClient, googlePayConfig); },
            buttonColor: 'default',
            buttonType: 'short'
        });
        const container = document.getElementById('container');
        container.innerHTML = '';
        container.appendChild(button);
    }

    async function onGooglePaymentButtonClicked(paymentsClient, googlePayConfig) {
        try {
            // create an order on server first to get orderID (PayPal Orders V2)
            const orderResp = await fetch('/api/orders', { method: 'POST' });
            const order = await orderResp.json();
            const orderID = order.id;
            log("Created server order:", orderID);

            // Build PaymentDataRequest per Google Pay; paypal.Googlepay().config() already returned allowedPaymentMethods and merchantInfo
            const paymentDataRequest = {
                apiVersion: 2,
                apiVersionMinor: 0,
                allowedPaymentMethods: googlePayConfig.allowedPaymentMethods,
                merchantInfo: googlePayConfig.merchantInfo,
                transactionInfo: {
                    totalPriceStatus: 'FINAL',
                    totalPrice: order.purchase_units[0].amount.value,
                    currencyCode: order.purchase_units[0].amount.currency_code
                },
                callbackIntents: ["PAYMENT_AUTHORIZATION"]
            };

            // Request payment sheet
            const paymentData = await paymentsClient.loadPaymentData(paymentDataRequest);
            log("Google Pay paymentData:", paymentData);

            // When Google Pay authorizes, confirm the order via paypal.Googlepay().confirmOrder()
            // PayPal component handles conversion and exchange with Google token
            const confirmResp = await paypal.Googlepay().confirmOrder({
                orderID: orderID,
                paymentData: paymentData
            });
            log("paypal.Googlepay().confirmOrder() =>", confirmResp);

            // Finally capture on server
            const capResp = await fetch('/api/orders/' + orderID + '/capture', { method: 'POST' });
            const capJson = await capResp.json();
            log("capture result:", capJson);

            alert("Payment complete: " + (capJson.status || JSON.stringify(capJson)));
        } catch (err) {
            console.error(err);
            log("Payment flow error:", err);
            alert("Payment failed: " + (err && err.message ? err.message : JSON.stringify(err)));
        }
    }
</script>
</body>
</html>
